<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/logo.png" alt="ZBOX Logo" class="logo" />
        <p class="subtitle">{{ isLoginMode ? '欢迎回来，请登录您的账号' : '创建新账号' }}</p>
      </div>

      <!-- 登录表单 -->
      <form v-if="isLoginMode" class="login-form" @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="account">账号</label>
          <div class="input-wrapper">
            <SvgIcon name="user" width="20" height="20" />
            <input
              id="account"
              v-model="loginForm.account"
              type="text"
              placeholder="请输入账号"
              autocomplete="username"
            />
          </div>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <div class="input-wrapper">
            <SvgIcon name="lock" width="20" height="20" />
            <input
              id="password"
              v-model="loginForm.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
              autocomplete="current-password"
            />
            <button type="button" class="toggle-password" @click="showPassword = !showPassword">
              <SvgIcon :name="showPassword ? 'eye-open' : 'eye-close'" width="20" height="20" />
            </button>
          </div>
        </div>

        <div class="form-options">
          <label class="remember-password">
            <input type="checkbox" v-model="loginForm.rememberPassword" />
            <span>记住密码</span>
          </label>
        </div>

        <button type="submit" class="login-button" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>

        <div class="register-link">
          还没有账号？ <a href="#" @click.prevent="toggleMode">立即注册</a>
        </div>
      </form>

      <!-- 注册表单 -->
      <form v-else class="login-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="register-username">用户名</label>
          <div class="input-wrapper">
            <SvgIcon name="user" width="20" height="20" />
            <input
              id="register-username"
              v-model="registerForm.username"
              type="text"
              placeholder="请输入用户名"
            />
          </div>
        </div>

        <div class="form-group">
          <label for="register-account">账号</label>
          <div class="input-wrapper">
            <SvgIcon name="user" width="20" height="20" />
            <input
              id="register-account"
              v-model="registerForm.account"
              type="text"
              placeholder="请输入账号"
            />
          </div>
        </div>

        <div class="form-group">
          <label for="register-password">密码</label>
          <div class="input-wrapper">
            <SvgIcon name="lock" width="20" height="20" />
            <input
              id="register-password"
              v-model="registerForm.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
            />
            <button type="button" class="toggle-password" @click="showPassword = !showPassword">
              <SvgIcon :name="showPassword ? 'eye-open' : 'eye-close'" width="20" height="20" />
            </button>
          </div>
        </div>

        <button type="submit" class="login-button" :disabled="isLoading">
          {{ isLoading ? '注册中...' : '注册' }}
        </button>

        <div class="register-link">
          已有账号？ <a href="#" @click.prevent="toggleMode">返回登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import SvgIcon from '@/components/SvgIcon.vue'
import { register, login } from '@/api/user'

const router = useRouter()
const showPassword = ref(false)
const isLoading = ref(false)
const isLoginMode = ref(true)

// 登录表单数据
const loginForm = reactive({
  account: '',
  password: '',
  rememberPassword: false,
})

// 注册表单数据
const registerForm = reactive({
  username: '',
  account: '',
  password: '',
})

// 组件挂载时检查是否有保存的账号密码
onMounted(() => {
  // 检查是否有保存的账号和密码
  const savedAccount = localStorage.getItem('zbox-account')
  const savedPassword = localStorage.getItem('zbox-password')

  if (savedAccount) {
    loginForm.account = savedAccount
    loginForm.rememberPassword = true

    // 如果同时保存了密码，则填充密码
    if (savedPassword) {
      loginForm.password = savedPassword
    }
  }
})

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
}

// 处理登录
const handleLogin = async () => {
  if (!loginForm.account || !loginForm.password) {
    alert('请输入账号和密码')
    return
  }

  try {
    isLoading.value = true

    const res = await login({
      account: loginForm.account,
      password: loginForm.password,
    })

    if (res.success) {
      // 保存token
      localStorage.setItem('zbox-token', res.data.token)

      // 根据是否选择"记住密码"保存账号密码和用户信息
      if (loginForm.rememberPassword) {
        localStorage.setItem('zbox-account', loginForm.account)
        localStorage.setItem('zbox-password', loginForm.password)
        localStorage.setItem('userInfo', JSON.stringify(res.data.user))
      } else {
        // 如果用户取消了记住密码，则清除之前保存的信息
        localStorage.removeItem('zbox-account')
        localStorage.removeItem('zbox-password')
        // 不保存登录状态时使用会话存储
        sessionStorage.setItem('userInfo', JSON.stringify(res.data.user))
      }

      // 登录成功后跳转到首页
      router.push('/')
    } else {
      console.error(res.msg || '登录失败，请重试')
    }
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerForm.username || !registerForm.account || !registerForm.password) {
    alert('请填写完整的注册信息')
    return
  }

  try {
    isLoading.value = true

    const res = await register({
      username: registerForm.username,
      account: registerForm.account,
      password: registerForm.password,
    })

    if (res.success) {
      alert('注册成功，请登录')
      // 注册成功后，切换到登录页面并填入刚注册的账号
      loginForm.account = registerForm.account
      isLoginMode.value = true

      // 清空注册表单
      registerForm.username = ''
      registerForm.account = ''
      registerForm.password = ''
    } else {
      alert(res.msg || '注册失败，请重试')
    }
  } catch (error) {
    console.error('注册失败:', error)
    alert('注册失败，请重试')
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f7;
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 16px;
  padding: 40px;
  width: 100%;
  max-width: 420px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  max-width: 100px;
  height: auto;
  margin-bottom: 16px;
}

.subtitle {
  color: #86868b;
  font-size: 16px;
}

.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #1d1d1f;
  font-weight: 500;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper :deep(svg) {
  position: absolute;
  left: 12px;
  color: #86868b;
  z-index: 1;
}

.input-wrapper input {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 1px solid #d2d2d7;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
}

/* 修改输入框focus时的样式，与AddTodo保持一致 */
.input-wrapper input:focus {
  outline: none;
  border-color: #4361ee;
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}

.input-wrapper input[type='password'],
.input-wrapper input[type='text'] {
  padding-right: 40px;
}

.toggle-password {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  color: #86868b;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toggle-password:hover {
  color: #1d1d1f;
}

.toggle-password :deep(svg) {
  position: static;
  left: auto;
}

.form-options {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 24px;
}

.remember-password {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #1d1d1f;
  font-size: 14px;
  cursor: pointer;
}

.remember-password input[type='checkbox'] {
  width: 16px;
  height: 16px;
  accent-color: #4361ee;
}

.login-button {
  width: 100%;
  padding: 14px;
  background-color: #4361ee;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.login-button:hover:not(:disabled) {
  background-color: #3a56d4;
}

.login-button:disabled {
  background-color: #d2d2d7;
  cursor: not-allowed;
}

.register-link {
  text-align: center;
  margin-top: 24px;
  font-size: 14px;
  color: #86868b;
}

.register-link a {
  color: #4361ee;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }
}
</style>
